#Dependency

#library packages
library(ggplot2)
library(dplyr)
library(data.table)

library(optparse)

option_list <- list(
  make_option("--i", default = "", type = "character", help = "input file"),
  make_option("--c", default = "", type = "character", help = "color file"),
  make_option("--order", default = "", type = "character", help = "order by"),
  make_option("--g", default = "", type = "character", help = "gene name"),
  make_option("--o", default = "", type = "character", help = "output png file")
)
opt <- parse_args(OptionParser(option_list = option_list))

#import source data
dep<-fread(opt$i) %>%
       as.data.frame()
rownames(dep)<-dep[,1]
gene <- opt$g
dep<-dep[,-1]
mypal<-read.table(opt$c)[,1] %>%
         as.character()

#dim gene and extract corresponding statitstics
order<-opt$order
dep.gene<-data.frame(cell = colnames(dep),dep = as.numeric(dep[gene,]))
if ( order == 'alphabet'){
  dep.gene$cell<-factor(dep.gene$cell,levels = dep.gene$cell)
} else if (order == 'dependency'){
  dep.gene<-arrange(dep.gene,desc(dep))
  dep.gene$cell<-factor(dep.gene$cell,levels = dep.gene$cell)
}

#plot
png(file=opt$o,width=3000,height=1200,res=300)
ggplot(dep.gene)+geom_col(aes(x=cell,y=dep,fill=cell),color='black')+
  scale_fill_manual(values = mypal)+
  theme_bw()+theme(legend.position = 'none')+labs(y='Gene Effect',x='Cell line')+
  theme(axis.text.x = element_text(angle=45,hjust = 1,vjust = 1),axis.title.x = element_blank(),
        plot.margin = unit(c(0,0,0,1),'lines'))
  #scale_y_continuous(labels = function(x)format(x,scientific = F))
dev.off()

#export csv
colnames(dep.gene)[1]<-'cell_line'
write.csv(dep.gene,file = paste('gene.csv',sep = ''),row.names = F)
